import ArticleItem from '@/components/ArticleItem';
import { useAppSelector } from '@/store';
import {
  getArticleListByIdAction,
  updateArticleListByIdAction,
} from '@/store/action/article';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';

type Props = {
  channel_id: number;
};

export default function ArticleList({ channel_id }: Props) {
  //  获取数据
  const { articles } = useAppSelector((state) => state.article);
  // 取出文章列表 注意数据为空时的处理
  const { results: list = [], pre_timestamp } = articles[channel_id] || {};
  // const list = articles[channel_id]?.results || [];
  // const pre_timestamp = articles[channel_id]?.pre_timestamp;
  const dispatch = useDispatch();
  const handleLoadMore = async () => {
    await dispatch(
      updateArticleListByIdAction({ channel_id, timestamp: pre_timestamp })
    );
  };
  const { channel_id: activeId } = useAppSelector((state) => state.channel);
  useEffect(() => {
    if (activeId !== channel_id) return;
    if (list.length) return;
    dispatch(getArticleListByIdAction({ channel_id }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channel_id, dispatch, activeId]);
  const handleRefresh = async () => {
    dispatch(getArticleListByIdAction({ channel_id }));
  };
  return (
    <PullToRefresh onRefresh={handleRefresh}>
      <div>
        {list.map((item) => {
          return <ArticleItem data={item} key={item.art_id} />;
        })}
        {/*  使用无限滚动组件 */}
        <InfiniteScroll
          loadMore={handleLoadMore}
          hasMore={!!pre_timestamp}
        ></InfiniteScroll>
      </div>
    </PullToRefresh>
  );
}
